<template>
  <div class="container">
    <navigate>编辑障碍等级</navigate>
    <div class="title flex_align_center">
      <div class="bar"></div>
      <div class="text">用户残障等级情况表</div>
    </div>
    <div class="card" v-for="(e, i) in list" :key="i">
      <div class="header flex_row flex_align_center">
        <div class="title">残障情况{{ i + 1 }}</div>
        <div @click="del(i)" class="delete flex_align_center flex_row">
          <img src="@/assets/images/userRecord/delete.png" alt="" />
          删除
        </div>
      </div>
      <template v-for="(item, i) in e.list">
        <van-cell-group
          class="input_outer father_relative"
          :key="i + '_'"
          v-if="item.name == '障碍等级'"
        >
          <van-field
            readonly
            clickable
            v-model="item.val"
            :label="item.name"
            placeholder="请选择"
            @click="item.visible = true"
          />

          <v-picker
            :columns="disabilityLevel"
            valueKey="val"
            @confirm="
              item.val = $event.val;
              item.visible = false;
            "
            :isVisible="item.visible"
            @cancel="item.visible = false"
          />

          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>

        <van-cell-group :key="i + '-++'" class="input_outer" v-else>
          <van-field
            v-model="item.val"
            :label="item.name"
            placeholder="请输入"
          />
        </van-cell-group>
        <!-- 记录问题 ID -->
        <input type="hidden" v-model="item.pid" />
        <!-- 记录 item ID -->
        <input type="hidden" v-model="item.id" />
      </template>
    </div>

    <button @click="save" class="btn">保存资料</button>
    <button @click="add" class="add flex_row flex_align_center">
      <img src="@/assets/images/userRecord/add.png" alt="" />
      添加残障情况
    </button>
  </div>
</template>

<script>
import {
  getTemplateList,
  submitSelfAssessment,
  queryArchivesResults,
} from "@/api/funcation/selfAssessment";
import { mapState } from "vuex";
export default {
  data() {
    return {
      list: [],
      disabilityLevel: [
        {
          val: "一级残疾",
          value: "1",
        },
        {
          val: "二级残疾",
          value: "2",
        },
        {
          val: "三级残疾",
          value: "3",
        },
        {
          val: "四级残疾",
          value: "4",
        },
        {
          val: "五级残疾",
          value: "5",
        },
        {
          val: "六级残疾",
          value: "6",
        },
        {
          val: "七级残疾",
          value: "7",
        },
        {
          val: "八级残疾",
          value: "8",
        },
        {
          val: "九级残疾",
          value: "9",
        },
        {
          val: "十级残疾",
          value: "10",
        },
      ],
    };
  },
  computed: {
    ...mapState(["INFO"]),
  },
  methods: {
    async getArchivesResults() {
      let par = {
        user_id: this.INFO.id,
        type_id: 4,
      };
      try {
        let res = await queryArchivesResults(par);
        if (res.code === 200 && res.data && res.data.length > 0) {
          // 清空现有列表
          this.list = [];
          // 循环处理每个回显数据
          for (const item of res.data) {
            if (item.content) {
              try {
                const content = JSON.parse(item.content);
                console.log("解析后的回显数据:", content);
                // 确保模板已获取
                if (this.list.length === 0) {
                  await this.getTemplate();
                }
                // 添加足够的卡片来展示数据
                while (this.list.length < content.answerIds.length) {
                  this.add();
                }
                this.echoDataToForm(content);
              } catch (parseError) {
                console.error("解析单个回显数据失败:", parseError);
              }
            }
          }
        }
      } catch (error) {}
    },
    echoDataToForm(content) {
      const { questionIds, answerIds } = content;
      if (!questionIds || !answerIds) {
        return;
      }

      // 确保有足够的卡片来展示所有答案
      while (this.list.length < answerIds.length) {
        this.add();
      }

      // 遍历每个卡片并填充数据
      answerIds.forEach((cardAnswers, cardIndex) => {
        if (cardIndex < this.list.length) {
          const card = this.list[cardIndex];
          card.list.forEach((item) => {
            const qIndex = questionIds.findIndex(
              (qId) => Number(qId) === Number(item.id)
            );
            if (qIndex !== -1 && qIndex < cardAnswers.length) {
              const answer = cardAnswers[qIndex];
              if (item.name === "障碍等级") {
                const level = this.disabilityLevel.find(
                  (level) => level.value === String(answer)
                );
                this.$set(item, "val", level ? level.val : answer || "");
              } else {
                this.$set(item, "val", answer || "");
              }
            }
          });
        }
      });
    },

    async getTemplate(callback) {
      const res = await getTemplateList({ id: "4" });
      if (res.code == 200) {
        this.list.push({ list: res.data[0].templates[0].children });
        this.list.forEach((item) => {
          this.$set(item.list[1], "visible", false);
          item.list.forEach((e) => {
            this.$set(e, "val", "");
          });
        });

        callback && callback();
      }
    },
    async save() {
      const questionIds = [];
      const answerIds = [];

      this.list.forEach((card) => {
        const cardAnswers = []; // 存储当前卡片的所有答案

        card.list.forEach((item) => {
          // 确保 questionIds 不重复
          if (!questionIds.includes(item.id)) {
            questionIds.push(item.id);
          }

          // 根据问题类型处理答案
          if (item.name === "障碍等级") {
            // 直接使用 item.val 作为答案值（假设已经是 "1", "2" 等）
            const selectedLevel = this.disabilityLevel.find(
              (level) => level.val === item.val
            );
            cardAnswers.push(selectedLevel ? selectedLevel.value : item.val);
          } else {
            // 其他类型问题，直接使用 val
            cardAnswers.push(item.val);
          }
        });
        answerIds.push(cardAnswers);
      });

      // 构建最终参数
      const formattedParams = {
        questionIds: questionIds,
        answerIds: answerIds,
      };

      let par = {
        content: JSON.stringify(formattedParams), // 需要序列化为 JSON 字符串
        user_id: this.INFO.id,
        type_id: 4,
        source: 1,
      };
      const res = await submitSelfAssessment(par);
      if (res.code === 200) {
        this.$toast.success("修改成功！");
      }
    },

    del(i) {
      try {
        if (this.list.length == 1) return this.$toast.fail("已经是最后一条了!");
        this.list.splice(i, 1);
      } catch (error) {}
    },
    add() {
      let temp = [];
      this.list.forEach((ele) => {
        ele.list.forEach((item, index) => {
          temp[index] = JSON.parse(JSON.stringify(item));
          temp[index].val = "";
        });
      });

      this.list.push({ list: temp });
    },
  },
  created() {
    this.getTemplate(() => {
      this.getArchivesResults();
    });
  },
};
</script>

<style lang="less" scoped>
@import "../styles/common.less";
@import "./css/index.less";
</style>
